package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.wemedia.WemediaConstants;
import com.heima.common.exception.CustException;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dtos.WmMaterialDTO;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@Service
@Slf4j
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {
    @Autowired
    FileStorageService fileStorageService;

    @Resource
    WmNewsMaterialMapper wmNewsMaterialMapper;

    @Value("${file.oss.prefix}")
    String prefix;

    @Value("${file.oss.web-site}")
    String webSite;

    @Override
    public ResponseResult<WmMaterial> uploadPicture(MultipartFile multipartFile) {
        // 1 参数校验
        if (multipartFile == null || multipartFile.getSize() == 0) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "请上传正确的文件");
        }
        // 当前线程中获取用户ID
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }
        String originalFilename = multipartFile.getOriginalFilename();
        if (!checkFileSuffix(originalFilename)) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "请上传正确的素材格式,[jpg,jpeg,png,gif]");
        }
        // 2 上传到oss
        String fileId = null;
        try {
            String filename = UUID.randomUUID().toString().replace("-", "");
            int index = originalFilename.lastIndexOf(".");
            String suffix = originalFilename.substring(index);
            String originalFilenamePrefix = originalFilename.substring(0, index) + "-";
            fileId = fileStorageService.store(prefix, originalFilenamePrefix + filename + suffix, multipartFile.getInputStream());
            log.info("阿里云OSS 文件 fileId: {}", fileId);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("阿里云文件上传失败 uploadPicture error: {}", e);
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR, "服务器繁忙请稍后重试");
        }

        // 3 封装数据并保持到素材库中
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setIsCollection((short) 0);
        wmMaterial.setType((short) 0);
        wmMaterial.setCreatedTime(new Date());
        // 设置文件id
        wmMaterial.setUrl(fileId);
        wmMaterial.setUserId(user.getId());
        save(wmMaterial);
        // 前端显示
        wmMaterial.setUrl(webSite + fileId);
        // 4 返回结果
        return ResponseResult.okResult(wmMaterial);
    }


    /**
     * 检查文件格式 目前仅仅支持jpg  jpeg  png  gif 图片的上传
     *
     * @param path
     * @return
     */
    private boolean checkFileSuffix(String path) {
        if (StringUtils.isBlank(path)) return false;
        List<String> allowSuffix = Arrays.asList("jpg", "jpeg", "png", "gif");
        boolean isAllow = false;
        for (String suffix : allowSuffix) {
            if (path.endsWith(suffix)) {
                isAllow = true;
                break;
            }
        }
        return isAllow;
    }

    /**
     * 根据wmUserId查询指定用户的ID
     * @param wmMaterialDTO WM 材料 DTO
     * @return 通用的结果返回类
     */
    @Override
    public ResponseResult findListByWmUserId(WmMaterialDTO wmMaterialDTO) {

        // 0. 尝试获取用户Id
        WmUser wmUser = WmThreadLocalUtils.getUser();
        if(wmUser == null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "获取用户ID失败");
        }
        Integer wmUserId = wmUser.getId();

        if (wmMaterialDTO == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "参数不能为空");
        }
        // 1. 尝试校验并纠正参数
        wmMaterialDTO.checkParam();
        Short isCollection = wmMaterialDTO.getIsCollection();
        Integer size = wmMaterialDTO.getSize();
        Integer page = wmMaterialDTO.getPage();

        if(isCollection != null &&
                !WemediaConstants.COLLECT_MATERIAL.equals(isCollection) &&
                !WemediaConstants.CANCEL_COLLECT_MATERIAL.equals(isCollection)){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "isCollection参数仅能为null或0或1");
        }

        LambdaQueryWrapper<WmMaterial> lambdaWrapper = Wrappers.<WmMaterial>lambdaQuery();
        // isCollection=null,即查询全部
        if (WemediaConstants.COLLECT_MATERIAL.equals(isCollection)){
            // 若查询收藏的素材，加上限制条件
            lambdaWrapper.eq(WmMaterial::getIsCollection, WemediaConstants.COLLECT_MATERIAL);
        }
        // 2. 根据wmUserId分页查询素材；创建时间逆序
        IPage<WmMaterial> materialPage = new Page<>(page, size);
        materialPage = this.page(
                materialPage,
                        lambdaWrapper
                        .eq(WmMaterial::getUserId, wmUserId)
                        .orderByDesc(WmMaterial::getCreatedTime)
        );
        List<WmMaterial> records = materialPage.getRecords();

        // 将素材的url加上前缀web-size
        records = records.stream().map(material -> {
            material.setUrl(webSite + material.getUrl());
            return material;
        }).collect(Collectors.toList());

        ResponseResult responseResult = new PageResponseResult(page, size, materialPage.getTotal());
        responseResult.setData(records);
        return responseResult;
    }

    @Override
    public ResponseResult delPicture(Integer wmMaterialId) {
        // 1.查询该id对应的素材有没有
        WmMaterial wmMaterialById = this.getById(wmMaterialId);
        if (wmMaterialById == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "该id对应的素材不存在");
        }

        // 2. 查询该素材有没有被文章引用，若已应用，则不能删除
        Integer count = wmNewsMaterialMapper.selectCount(
                Wrappers
                        .<WmNewsMaterial>lambdaQuery()
                        .eq(WmNewsMaterial::getMaterialId, wmMaterialId)
        );
        if(count > 0){ // 被多个文章引用，不能删除
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "该素材已被引用，不能删除");
        }else{
            // 3. 删除素材
            this.removeById(wmMaterialId);
            // 4. 删除oss上的文件
            fileStorageService.delete(wmMaterialById.getUrl());
        }
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult updateMaterialCollection(Integer materialId, Short isCollection) {
        // 1. 查询目标素材是否存在
        WmMaterial wmMaterial = this.getById(materialId);
        if(wmMaterial == null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "该素材已不存在，无法修改");
        }

        // 2. 修改素材的是否收藏状态
        wmMaterial.setIsCollection(isCollection);
        boolean updateById = this.updateById(wmMaterial);
        if(!updateById){
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR, "修改素材收藏状态失败");
        }
        return ResponseResult.okResult();
    }
}